"""


"""
from django.db import transaction
from rest_framework import serializers
from goods.models import SKU, GoodsCategory, SPU, SPUSpecification, SpecificationOption, SKUSpecification


class SpecsSerializer(serializers.Serializer):

    spec_id = serializers.IntegerField(read_only=True)

    option_id = serializers.IntegerField(read_only=True)


class SKUSerializer(serializers.ModelSerializer):
    # 重写spu
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()

    # 重写category
    category = serializers.StringRelatedField(read_only=True)
    category_id = serializers.IntegerField()

    specs = SpecsSerializer(read_only=True, many=True)

    class Meta:
        model = SKU
        fields = "__all__"

    # 重写create方法进行入库
    @transaction.atomic
    def create(self, validated_data):

        # 记录还原点
        sid = transaction.savepoint()

        try:
            # 入库tb_SKU
            sku = SKU.objects.create(**validated_data)

            # 取出specs数据, 由于Validate_data 没有带上specs数据，只能通过其他方式取得
            data_dict = self.context.get("request").data

            # 获取里面的specs数据入库
            for spec_data in data_dict["specs"]:
                SKUSpecification.objects.create(sku=sku, spec_id=spec_data["spec_id"], option_id=spec_data["option_id"])

        except:
            transaction.rollback(sid)
            raise serializers.ValidationError("创建sku或者规格失败了...")

        return sku

    # 重写update方法更新数据
    @transaction.atomic()
    def update(self, instance, validated_data):

        sid = transaction.savepoint()

        try:
            # 更新数据
            SKU.objects.filter(id=instance.id).update(**validated_data)

            data_dict = self.context.get("request").data

            for spec_data in data_dict["specs"]:
                SKUSpecification.objects.filter(sku_id=instance.id, spec_id=spec_data["spec_id"]).update(option_id=spec_data["option_id"])

            new_sku = SKU.objects.get(id=instance.id)

        except:
            transaction.rollback(sid)
            raise serializers.ValidationError("修改sku或者规格失败了...")

        return new_sku


class SKUCategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = ("id", "name")


class SPUCategorySerializer(serializers.ModelSerializer):

     class Meta:
         model = SPU
         fields = ("id", "name")


class SpecificationOptionSerializer(serializers.ModelSerializer):

    class Meta:
        model = SpecificationOption
        fields = ("id", "value")


class SPUSpecsSerializer(serializers.ModelSerializer):

    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField(read_only=True)

    options = SpecificationOptionSerializer(read_only=True, many=True)

    class Meta:
        model = SPUSpecification
        # fields = "__all__"
        exclude = ("create_time", "update_time")




